package model

import (
	"github.com/jinzhu/gorm"
)

type UserAddress struct {
	*Model
	UserId       uint32 `json:"user_id"`
	Province     string `json:"province"`
	City         string `json:"city"`
	District     string `json:"district"`
	Address      string `json:"address"`
	Zip          string `json:"zip"`
	ContactName  string `json:"contact_name"`
	ContactPhone string `json:"contact_phone"`
	LastUsedAt   string `json:"last_used_at"`
	DeletedAt    string `json:"deleted_at"`
}

func (ua UserAddress) TableName() string {
	return "user_addresses"
}

//type TagSwagger struct {
//	List  []*Tag
//	Pager *app.Pager
//}

func (ua UserAddress) Count(db *gorm.DB) (int, error) {
	var count int
	//if t.Name != "" {
	//	db = db.Where("name = ?", t.Name)
	//}
	//db = db.Where("state = ?", t.State)
	if err := db.Model(&ua).Where("user_id = ?", ua.UserId).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

func (ua UserAddress) List(db *gorm.DB, pageOffset, pageSize int) ([]*UserAddress, error) {
	var address []*UserAddress
	var err error
	if pageOffset >= 0 && pageSize > 0 {
		db = db.Offset(pageOffset).Limit(pageSize)
	}
	db = db.Where("user_id = ?", ua.UserId)
	if err = db.Where("is_del = ?", 0).Find(&UserAddress{}).Error; err != nil {
		return nil, err
	}

	return address, nil
}

//
//func (t Tag) ListByIDs(db *gorm.DB, ids []uint32) ([]*Tag, error) {
//	var tags []*Tag
//	db = db.Where("state = ? AND is_del = ?", t.State, 0)
//	err := db.Where("id IN (?)", ids).Find(&tags).Error
//	if err != nil && err != gorm.ErrRecordNotFound {
//		return nil, err
//	}
//
//	return tags, nil
//}

func (ua UserAddress) Get(db *gorm.DB) (UserAddress, error) {
	var address UserAddress
	err := db.Where("id = ? ", ua.ID).First(&address).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return address, err
	}

	return address, nil
}

func (ua UserAddress) Create(db *gorm.DB) error {
	return db.Create(&ua).Error
}

func (ua UserAddress) Update(db *gorm.DB, values interface{}) error {
	return db.Model(&ua).Where("id = ?", ua.ID).Updates(values).Error
}

func (ua UserAddress) Delete(db *gorm.DB) error {
	return db.Where("id = ?", ua.Model.ID).Delete(&ua).Error
}
